<style lang="less">
  @import 'articles.less';
</style>
<template>
  <div>
    <Row>
      <Col span="24">
        <Card>
          <p slot="title" style="height: 32px">
            <Button v-checkPermission="'admin/article.Category/add'" type="primary" @click="alertAdd" icon="md-add">{{ $t('add_button') }}</Button>&nbsp;
          </p>
          <div>
            <Table :loading="listLoading" row-key="id" :columns="columnsList" :data="tableData" border></Table>
          </div>
        </Card>
      </Col>
    </Row>
    <Modal v-model="modalSetting.show" width="60%" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>{{formItem.id ? '编辑' : '新增'}}分类</span>
      </p>
      <Row>
        <Col span="18" push="5">
          <Card dis-hover :bordered="false" :shadow="false" >
            <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="80">
              <FormItem label="名称" prop="name">
                <Input v-model="formItem.name" placeholder="请输入名称"></Input>
              </FormItem>
              <FormItem label="描述" prop="description">
                <Input v-model="formItem.description" type="textarea" :rows="4" placeholder="请输入描述"></Input>
              </FormItem>
            </Form>
          </Card>
          </Col>
          <Col span="5" pull="18">
            <Card :shadow="false" dis-hover>
              <p slot="title">父级分类</p>
              <Tree :check-strictly="true"  :data="categoryTree" ref="category"></Tree>
            </Card>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="text" @click="cancel" style="margin-right: 8px">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { forEach } from '@/libs/tools'
const addSubButton = (vm, h, currentRow, index) => {
  return h('Button', {
    props: {
      type: 'success'
    },
    style: {
      margin: '0 5px'
    },
    on: {
      'click': () => {
        var item = {
          id: 0,
          name: '',
          parent_id: currentRow.id,
          parent_path: currentRow.parent_path,
          description: ''
        }
        let list = JSON.parse(JSON.stringify(vm.tableData))
        vm.categoryTree = vm.handleCategory(list, item)
        vm.formItem = item
        vm.modalSetting.show = true
        vm.modalSetting.index = index
      }
    }
  }, '添加子类')
}
const editButton = (vm, h, currentRow, index) => {
  return h('Button', {
    props: {
      type: 'primary'
    },
    style: {
      margin: '0 5px'
    },
    on: {
      'click': () => {
        var item = {
          id: currentRow.id,
          name: currentRow.title,
          parent_id: currentRow.parent_id,
          description: currentRow.description
        }
        let list = JSON.parse(JSON.stringify(vm.tableData))
        vm.categoryTree = vm.handleCategory(list, currentRow)
        vm.formItem = item
        vm.modalSetting.show = true
        vm.modalSetting.index = index
      }
    }
  }, vm.$t('edit_button'))
}
const deleteButton = (vm, h, currentRow, index) => {
  return h('Poptip', {
    props: {
      confirm: true,
      title: '您确定要删除这条数据吗? ',
      transfer: true
    },
    on: {
      'on-ok': () => {
        vm.$easyAjax({ url: 'Article/categoryDelete/' + (currentRow.id), method: 'delete' }).then(response => {
          if (response.data.code) {
            currentRow.loading = false
            vm.getList()
          } else {
            vm.$Message.error(response.data.msg)
          }
        })
      }
    }
  }, [
    h('Button', {
      style: {
        margin: '0 5px'
      },
      props: {
        type: 'error',
        placement: 'top',
        loading: currentRow.isDeleting
      }
    }, vm.$t('delete_button'))
  ])
}
export default {
  name: 'system_menu',
  data () {
    return {
      actionType: 'add',
      expandList: [],
      initCategoryData: [],
      categoryTree: [],
      columnsList: [
        {
          title: '名称',
          align: 'left',
          key: 'title',
          tree: true
        },
        {
          title: 'ID',
          key: 'id',
          width: 120
        },
        {
          title: '是否发布',
          align: 'center',
          width: 100,
          render: (h, params) => {
            let vm = this
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: params.row.status
              },
              on: {
                'on-change': function (status) {
                  vm.$easyAjax({ url: 'Article/changeCategoryStatus/' + (params.row.id), data: { status: status }, method: 'put' }).then(response => {
                    if (response.data.code) {
                      vm.$Message.success(response.data.msg)
                      // vm.getList()
                    } else {
                      vm.$Message.error({
                        content: response.data.msg,
                        duration: 10,
                        closable: true
                      })
                    }
                  })
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, '是'),
              h('span', {
                slot: 'close'
              }, '否')
            ])
          }
        },
        {
          title: '操作',
          align: 'center',
          key: 'handle',
          width: 300,
          render: (h, params) => {
            return h('div', [
              addSubButton(this, h, params.row, params.index),
              editButton(this, h, params.row, params.index),
              deleteButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      listLoading: false,
      tableData: [],
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      formItem: {
        id: 0,
        name: '',
        parent_id: '',
        description: 0
      },
      ruleValidate: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getList()
  },
  watch: {
    tableData: {
      handler: function (val, oldVal) {
        let vm = this
        vm.setExpandList(JSON.parse(JSON.stringify(val)))
      },
      deep: true
    }
  },
  methods: {
    setExpandList (list) {
      let vm = this
      forEach(list, item => {
        let obj = item
        if (obj._showChildren) {
          if (!(vm.expandList).includes(obj.id)) {
            vm.expandList.push(obj.id)
          }
        } else {
          if ((vm.expandList).includes(obj.id)) {
            for (var i in vm.expandList) {
              vm.expandList.splice(i, 1)
            }
          }
        }
        if (obj.children) {
          obj.children = vm.setExpandList(item.children)
        }
      })
    },
    handleCategoryTable (list) {
      let vm = this
      let res = []
      forEach(list, item => {
        let obj = item
        if ((vm.expandList).includes(obj.id)) {
          vm.$set(obj, '_showChildren', true)
        }
        if (obj.children) {
          obj.children = vm.handleCategoryTable(item.children)
        }
        res.push(obj)
      })
      return res
    },
    alertAdd () {
      let vm = this
      var item = {
        id: 0,
        name: '',
        parent_id: '',
        description: ''
      }
      vm.formItem = item
      vm.modalSetting.show = true
    },
    handleCategory (list, currentRow) {
      let vm = this
      let res = []
      forEach(list, item => {
        let obj = item
        if (obj.id !== currentRow.id) {
          if ((currentRow.parent_path).includes(obj.id)) {
            vm.$set(obj, 'expand', true)
          }
          if (obj.id === currentRow.parent_id) {
            vm.$set(obj, 'selected', true)
          } else {
            vm.$set(obj, 'selected', false)
          }
          if (obj.children) {
            obj.children = vm.handleCategory(item.children, currentRow)
          }
          res.push(obj)
        }
      })
      return res
    },
    submit () {
      let vm = this
      let ruleNodes = vm.$refs['category'].getSelectedNodes()
      if (ruleNodes.length > 0) {
        vm.formItem.parent_id = ruleNodes[0].id
      } else {
        vm.formItem.parent_id = 0
      }
      vm.$refs['myForm'].validate((valid) => {
        if (valid) {
          vm.modalSetting.loading = true
          let method = 'POST'
          let url = 'Article/categoryAdd'
          if (vm.formItem.id > 0) {
            method = 'PUT'
            url = 'Article/categoryEdit/' + (vm.formItem.id)
          }
          vm.$easyAjax({ url: url, data: vm.formItem, method: method }).then(response => {
            vm.$Message.success(response.data.msg)
            vm.getList()
            vm.cancel()
          })
        }
      })
    },
    cancel () {
      this.modalSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.$refs['myForm'].resetFields()
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    getList () {
      let vm = this
      vm.listLoading = true
      this.$easyAjax({ url: 'Article/categoryIndex' }).then(response => {
        vm.listLoading = false
        vm.tableData = vm.handleCategoryTable(response.data.data.list)
        vm.categoryTree = JSON.parse(JSON.stringify(response.data.data.list))
        vm.initCategoryData = JSON.parse(JSON.stringify(response.data.data.list))
      })
    }
  }
}
</script>
